package com.fenxiangtech.mall.service.impl;

import com.fenxiangtech.mall.dto.SerializeWrapper;
import com.fenxiangtech.mall.exception.RedisCacheException;
import com.fenxiangtech.mall.exception.TokenInvalidException;
import com.fenxiangtech.mall.service.TokenService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author zhangjiashun
 */
@Service
public class TokenServiceImpl implements TokenService {


    private String tokenSalt = "Js957";

    @Autowired
    private HttpServletRequest request;

//    @Autowired
//    private RedisDao<SerializeWrapper<Map>> redisDao;

    @Override
    public String generateToken() {
        String randChar = RandomStringUtils.randomAlphanumeric(32);
        long timeMillis = System.currentTimeMillis();
        String tokenBase = randChar + timeMillis + tokenSalt;
        return DigestUtils.md5DigestAsHex(tokenBase.getBytes());
    }

    @Override
    public void verifyToken() {
        this.getTokenInfo();
    }

    protected Map<String, String> getTokenInfo() {
        String token = request.getHeader("token");
        if (token == null) {
            throw new TokenInvalidException();
        }
        SerializeWrapper<Map> serializeWrapper = new SerializeWrapper<>();
//        serializeWrapper = redisDao.getValue(token, serializeWrapper);
        serializeWrapper = null;
        if (serializeWrapper == null) {
            throw new TokenInvalidException();
        }
        return serializeWrapper.getData();
    }

    protected String saveToCache(String key, SerializeWrapper<Map> value) {
//        String result = redisDao.putValue(key, value);
        String result = null;
        if (!"OK".equals(result)) {
            throw new RedisCacheException();
        }
        return key;
    }
}
